# src/core/ormdb.py
# pip install  sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from src.core import crypt_utils as cryptU
from src.core.config import Config
from urllib.parse import quote

# 数据库连接配置
# DATABASE_URL = "mysql+mysqlconnector://username:password@localhost/dbname"
# 构建数据库连接字符串
DB_TYPE = Config.DB_TYPE
DB_USER = cryptU.aes_decrypt(Config.DB_USERNAME)
DB_PASSWORD = quote(cryptU.aes_decrypt(Config.DB_PASSWORD))
DB_HOST = cryptU.aes_decrypt(Config.DB_HOST)
DB_NAME = cryptU.aes_decrypt(Config.DB_SID)

if DB_TYPE == 'mysql':
    DATABASE_URL = f"mysql+mysqlconnector://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}"
elif DB_TYPE == 'oracle':
    DATABASE_URL = f"oracle+cx_oracle://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}"
elif DB_TYPE == 'sql_server':
    DATABASE_URL = f"mssql+pyodbc://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}?driver=ODBC Driver 17 for SQL Server"
# 创建数据库引擎
# print(DATABASE_URL)
engine = create_engine(DATABASE_URL)

# 创建会话类
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 声明基类
Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
